<script setup lang="ts">
import { Search, ArrowDown, ArrowUp } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { getUserListApi, delUserApi, updateUserApi, assignUserRoleApi } from '@/api/user'
import type { UserRes } from '@/types/user'
import { useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import { checkMoible } from '@/utils/validate'
import { getRoleListApi } from '@/api/role'
import type { RoleListRes } from '@/types/role'

const router = useRouter()

// 筛选区域收缩效果
const expand = ref(false)

//用户列表查询数据

const formData = ref({
  pagenum: 1,
  pagesize: 10,
  username: '',
  mobile: '',
  role_name: '',
  created_at: '',
  updated_at: '',
})

// 重置筛选表单数据
const reset = () => {
  formData.value = {
    pagenum: 1,
    pagesize: 10,
    username: '',
    mobile: '',
    role_name: '',
    created_at: '',
    updated_at: '',
  }
  getUserList()
}

const userList = ref([] as UserRes[])
const total = ref(0)
const getUserList = async () => {
  const res = await getUserListApi(formData.value)
  // console.log(res)
  userList.value = res.data.list as UserRes[]
  total.value = res.data.total as number
}
getUserList()

const handleSizeChange = (newSize: number) => {
  formData.value.pagesize = newSize
  getUserList()
}
const handleCurrentChange = (newPage: number) => {
  formData.value.pagenum = newPage
  getUserList()
}

//删除用户
const delUser = async (userInfo: UserRes) => {
  // 删除提示确认框
  const flag = await ElMessageBox.confirm('确定要删除该用户码?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).catch((error) => error)

  if (flag === 'cancel') return

  const res = await delUserApi(userInfo)

  // 判断删除失败的情况
  if (res.data.state !== 200) {
    return ElMessage.error(res.data.msg)
  }
  // 删除成功提示
  ElMessage.success('删除用户成功')
  // 重新加载一次用户数据
  getUserList()
}

//------------------修改用户start-------------
const editUserVisible = ref(false)
const formRef = ref()
const editForm = ref()

const validateMobile = (rule: object, value: string, callback: (arg0?: object) => void) => {
  if (checkMoible(value)) {
    callback()
  } else {
    callback(new Error('手机号不合法'))
  }
}

const formRules = {
  username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  password: [{ min: 6, max: 12, message: '密码长度应在6~12位之间', trigger: 'blur' }],
  mobile: [{ validator: validateMobile, trigger: 'blur' }],
}
const editUser = (row: UserRes) => {
  // 1.弹出框显示
  // 2.用户数据回显
  //    2.1 可以通过作用域插槽传参的形式得到用户的信息  （当前项目）
  //    2.2 可以通过用户id,发送ajax请求获取当前用户的数据
  editUserVisible.value = true
  editForm.value = row
}

// 用户更新
const updateUser = () => {
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return

    // ajax更新用户
    const res = await updateUserApi(editForm.value as UserRes)

    // 更新失败
    if (res.data.state !== 200) {
      ElMessage.error(res.data.msg)
    }

    // 更新成功
    ElMessage.success('更新成功')

    // 关闭对话框
    editUserVisible.value = false

    // 重新获取数据
    getUserList()
  })
}

// 重置数据并移除数据不合法提示
const resetEditUser = () => {
  formRef.value.resetFields()
}

//弹出框关闭
const handleEditClose = () => {
  resetEditUser()
}
//------------------修改用户end-------------

// 分配角色
const editRoleVisible = ref(false)

// 获取角色列表数据
const roleList = ref([] as RoleListRes[])
const getRoleList = async () => {
  const res = await getRoleListApi(formData.value)
  roleList.value = res.data.list as RoleListRes[]
  total.value = res.data.total as number
}
getRoleList()

const assignRoleForm = ref({
  username: '',
  role_name: '',
  role_id: '',
  user_id: 0,
})
const editRole = (row: UserRes) => {
  // 1.显示弹出框
  editRoleVisible.value = true

  // 2.弹出框中的表单数据回显
  assignRoleForm.value.username = row.username
  assignRoleForm.value.role_name = row.role_name
  assignRoleForm.value.user_id = row.user_id
}

const assignRole = async () => {
  // 1.ajax分配角色
  await assignUserRoleApi(assignRoleForm.value)

  // 2.关闭弹出框
  editRoleVisible.value = false

  // 3.成功提示
  ElMessage.success('分配角色成功')

  // 4.重新加载用户数据
  getUserList()
}
</script>

<template>
  <!-- 用户筛选区 -->
  <el-card>
    <el-form :inline="true" :model="formData">
      <el-form-item label="用户名">
        <el-input placeholder="请输入用户名" v-model="formData.username"></el-input>
      </el-form-item>
      <el-form-item label="手机号">
        <el-input placeholder="请输入手机号" v-model="formData.mobile"></el-input>
      </el-form-item>
      <el-form-item label="角色名" v-show="expand">
        <el-input placeholder="请输入角色名" v-model="formData.role_name"></el-input>
      </el-form-item>
      <el-form-item label="创建于" v-show="expand">
        <el-date-picker
          v-model="formData.created_at"
          type="daterange"
          range-separator="到"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          size="default"
        />
      </el-form-item>
      <el-form-item label="更新于" v-show="expand">
        <el-date-picker
          v-model="formData.updated_at"
          type="daterange"
          range-separator="到"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          size="default"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="getUserList">搜索</el-button>
        <el-button @click="reset">重置</el-button>
        <el-link type="primary" style="margin-left: 10px" @click="expand = !expand">
          {{ expand ? '收起' : '展开' }}
          <el-icon class="el-icon--right">
            <ArrowUp v-if="expand" />
            <ArrowDown v-else />
          </el-icon>
        </el-link>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 用户列表 -->
  <el-card style="margin-top: 10px">
    <template #header>
      <div class="card-header">
        <el-button type="danger">批量删除</el-button>
        <el-button type="primary" @click="router.push('/user/create')">添加</el-button>
      </div>
    </template>

    <!-- 
      作用域插槽：作用子组件将数据再传回给父组件

      <Son>
        <template v-slot="slotScoped">
          {{ slotScoped.abc }}
          <img :src="slotScoped.abc.avatar">
        </template>
      </Son>

      <slot abc='{usrenmae:xxx,avatar:xxxx}'></slot>


    -->

    <el-table :data="userList" style="width: 100%" max-height="400" border stripe>
      <el-table-column prop="user_id" label="编号" width="120" />
      <el-table-column prop="role_name" label="所属角色" width="120" />
      <el-table-column prop="avatar" label="头像" width="120">
        <template v-slot="{ row }">
          <img :src="row.avatar" alt="" style="width: 80px; height: 80px; border-radius: 50%" />
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="120" />
      <el-table-column prop="mobile" label="手机号" width="150" />
      <el-table-column prop="state" label="登录" width="120">
        <template v-slot="{ row }">
          <el-switch
            v-model="row.state"
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
            :active-value="1"
            :inactive-value="0"
          />
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建于" width="200" />
      <el-table-column prop="updated_at" label="更新于" width="200" />
      <el-table-column fixed="right" label="操作" min-width="220">
        <template v-slot="{ row }">
          <el-button type="primary" size="small" @click="editUser(row)">编辑</el-button>
          <el-button type="success" size="small" @click="editRole(row)">分配角色</el-button>
          <el-button type="danger" size="small" @click="delUser(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件
     current-page：当前显示页码值
     page-size：每页显示数据条数
     page-sizes：设置每页显示条数
     layout:布局
     total: 总条数

     size-change: 当每页显示数据的条数发生变化触发事件
     current-change：当页码值发生变化时触发事件
    -->
    <el-pagination
      style="margin-top: 15px"
      v-model:current-page="formData.pagenum"
      v-model:page-size="formData.pagesize"
      :page-sizes="[3, 5, 10, 20]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </el-card>

  <!-- 编辑用户弹出框 -->
  <el-dialog v-model="editUserVisible" title="编辑用户" width="800" @close="handleEditClose">
    <el-form ref="formRef" :model="editForm" :rules="formRules" label-width="auto" size="large">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="editForm.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="editForm.password" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="editForm.mobile" placeholder="请输入手机号"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="updateUser">更新用户</el-button>
        <el-button @click="resetEditUser"> 重置 </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 分配角色 -->
  <el-dialog v-model="editRoleVisible" title="分配角色" width="800">
    <el-form>
      <el-form-item label="当前用户">
        <el-input v-model="assignRoleForm.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="当前角色">
        <el-input v-model="assignRoleForm.role_name" disabled></el-input>
      </el-form-item>
      <el-form-item label="选择角色">
        <el-select v-model="assignRoleForm.role_id">
          <el-option
            :label="item.role_name"
            :value="item.role_id"
            :key="item.role_id"
            v-for="item in roleList"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="assignRole">立即更新</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<style scoped lang="scss"></style>
